<?php
/**
 * 第三方登录处理
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/6/4 16:10
 * @copyright PanxSoft Inc.
 */

namespace App\Services\OAuth;


use App\Models\Contracts\OAuthUser;
use App\Models\OpenWechat\WechatUser;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class UserThirdPartyService
{
    const OAUTH_TYPE_WECHAT = 'wechat_app';
    const OAUTH_TYPE_ALIPAY = 'alipay_app';

    const VALIDATE_OAUTH_TYPES = [
        self::OAUTH_TYPE_WECHAT,
        self::OAUTH_TYPE_ALIPAY,
    ];

    public function bindOAuthUser(User $user,
                                  string $oauth_type,
                                  int $oauth_user_id): ?OAuthUser
    {
        switch ($oauth_type) {
            case UserThirdPartyService::OAUTH_TYPE_WECHAT :
                return $this->bindOauthWechatUser($user, $oauth_user_id);

            case UserThirdPartyService::OAUTH_TYPE_ALIPAY :
                return $this->bindOauthAliPayUser($user, $oauth_user_id);

            default :
                return null;
        }
    }

    /**
     * @param Request $request
     * @param User $user
     *
     * @return OAuthUser|null
     */
    public function bindRequestOAuthUser(Request $request, User $user): ?OAuthUser
    {
        $oauth_type = $request->get('oauth_type');
        $oauth_user_id = $request->get('oauth_user_id');
        if (! ($oauth_type || $oauth_user_id)) {
            return null;
        }

        return $this->bindOAuthUser($user, $oauth_type, $oauth_user_id);
    }

    private function bindOauthWechatUser(User $user,
                                         int $wechat_user_id): ?WechatUser
    {
        $wechat_user = (new WechatUser)->find($wechat_user_id);
        if (! $wechat_user) {
            return null;
        }

        if ($wechat_user->user_id) { // user only has one
            return null;
        }

        $wechat_user->user()->associate($user)->save();

        if (! $user->avatar) {
            $user->update(['avatar' => $wechat_user->headimgurl]);
        };

        return $wechat_user;
    }

    private function bindOauthAliPayUser(User $user, int $ali_user_id): ?OAuthUser
    {
        return null;
    }
}